package com.sihai.common.config;

import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 对HttpServletRequest进行重写，
 * @author sihai
 */
public class RequestWrapper extends HttpServletRequestWrapper {
    // 参数字节数组
    private byte[] requestBody;
    // Http请求对象
    private HttpServletRequest request;

    private static AtomicInteger integer=new AtomicInteger(0);
    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        this.request = request;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        /**
         * 每次调用此方法时将数据流中的数据读取出来，然后再回填到InputStream之中
         * 解决通过@RequestBody和@RequestParam（POST方式）读取一次后控制器拿不到参数问题
         */
        if (null == this.requestBody&&integer.get()==0) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ServletInputStream inputStream = request.getInputStream();
            FileCopyUtils.copy(inputStream,baos);
            this.requestBody = baos.toByteArray();
        }

        final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }

            @Override
            public int read() {
                return bais.read();
            }
        };
    }

    public byte[] getRequestBody() {
        return requestBody;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}
